package com.srcbox.file.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.srcbox.file.R
import java.lang.Exception
import java.util.*

class MainOneList(private val list: ArrayList<String>, private val context: Context) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return MeViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.main_one_list_adapter,
                parent,
                false
            )
        )
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        holder as MeViewHolder
        holder.bind(holder.itemView, position)
    }

    override fun getItemViewType(position: Int): Int {
        return super.getItemViewType(position)
    }

    inner class MeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(itemView: View, p: Int) {
            val packName = list[p]
            val textV = itemView.findViewById<TextView>(R.id.text)
            val imgV = itemView.findViewById<ImageView>(R.id.img)
            try {
                imgV.setImageDrawable(context.packageManager.getApplicationIcon(packName))
                textV.text =
                    context.packageManager.getApplicationLabel(
                        context.packageManager.getApplicationInfo(
                            packName,
                            0
                        )
                    )
            } catch (e: Exception) {
                textV.text = "app"
            }
        }
    }
}